//配置基地址
const baseUrl = "https://meituan.thexxdd.cn/api";

//图片上传地址
export const IMAGEURL = baseUrl + "/upload_picture";

//AI智能智能识别
export const AIURL = baseUrl + "/ai_card";

import { Base64 } from "js-base64";

interface typeOptions {
  url: string;
  method: "GET" | "POST" | "PUT";
  data?: string | object | ArrayBuffer;
}

interface resData {
  data: { data: any[] };
  statusCode: number;
}

//获取加密后的token
const getToken = () => {
  //读取token
  const token = uni.getStorageSync("wxuser").user_Token || "";
  //拼接 :
  const tokenStr = token + ":";
  //加密
  const encodeToken = Base64.encode(tokenStr);

  console.log("加密结果：", "Basic " + encodeToken);

  return "Basic " + encodeToken;
};

const request = (options: typeOptions): Promise<resData> => {
  uni.showLoading({
    title: "正在加载中",
  });
  return new Promise((resolve, reject) => {
    uni.request({
      url: `${baseUrl}/${options.url}`,
      method: options.method,
      data: options.data,
      header: {
        authorization: getToken(),
      },
      success(res: any) {
        console.log("请求接口：", res);
        uni.hideLoading();
        console.log("返回结果：", res);
        if (res.statusCode === 200) {
          resolve(res);
        } else if (res.statusCode === 500) {
          uni.showToast({
            icon: "none",
            title: "表示服务器错误",
          });
        } else if (res.statusCode === 401) {
          console.log("401返回的内容：", res);
          uni.showToast({
            icon: "none",
            title: "表示没有权限访问接口数据",
          });

          //去登录页面，授权登录，拿到token，保存到本地
          uni.navigateTo({
            url: "/pages/login_page/index",
          });

          return Promise.reject("表示没有权限访问接口数据");
        } else if (res.statusCode === 202) {
          uni.showToast({
            icon: "none",
            title: res.data.msg,
          });
          return Promise.reject("表示某些字段没有填写");
        }
        if (res.statusCode === 400) {
          uni.showToast({
            icon: "none",
            title: "表示参数填写错误，往往是开发者填写参数不对造成的",
          });
          return Promise.reject("表示参数填写错误");
        }
      },
      fail(error) {
        console.log("error:", error);
      },
    });
  });
};

export default request;
